package com.example.othree.controller;

import com.example.othree.common.R;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/ozone-depletion-info")
public class OzoneDepletionController {

//    @Value("${custom.file-path}")
//    private String filePath = "G:\\学校\\研究生\\河北臭氧\\数据\\【6】臭氧格点化融合分析逐日浓度\\20130101-20240607-臭氧格点数据";
    private String filePath ="C:\\lt\\hebei\\backend\\sample_data";

    @ApiOperation("获取臭氧格点化融合分析逐日浓度")
    @GetMapping("/getByDate")
    public R getByDate(@RequestParam("date") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String formattedDate = date.format(formatter);
        String file = filePath + "/" + formattedDate + "_O3_v2.csv";

        // 创建嵌套的HashMap来存储 (X_Lon -> (Y_Lat -> M8H_O3))
        Map<Double, Map<Double, Double>> ozoneMap = new HashMap<>();
        // 读取CSV文件并填充嵌套的HashMap
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.contains("X_Lon")){
                    continue;
                }
                // 分割CSV行
                String[] fields = line.split(","); // 假设CSV使用制表符分隔符，如果使用逗号，请改为","

                // 提取X_Lon, Y_Lat和M8H_O3值
                double lon = Double.parseDouble(fields[1]);
                double lat = Double.parseDouble(fields[2]);
                double o3Value = Double.parseDouble(fields[3]);

                // 如果外层HashMap中没有该X_Lon，创建一个新的内层HashMap
                ozoneMap.putIfAbsent(lon, new HashMap<>());

                // 将Y_Lat和M8H_O3值放入内层HashMap
                ozoneMap.get(lon).put(lat, o3Value);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return R.error().message("文件未找到");
        } catch (IOException e) {
            e.printStackTrace();
            return R.error().message("出现了未知错误");
        }

        return R.ok().data("ozone_matrix", ozoneMap);
    }

}
